import { Button, Form, FormInstance, Input, Modal, Pagination, Select, Table, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { classRoomsList, teacherList, coursesList, timeSlotList } from "../../../api/common";
import * as lessonsSort from '../../../api/course/lessonsSort'
import { CreatedType, SearchType } from '../../../api/course/lessonsSort';
import useBseGeneraHook from '../../../components/BaseGeneraForm/hook';
import { BaseGeneraForm } from '../../../components';
import moment from 'moment';

interface selectObject {
  classRoomsList: any[], // 教室
  teacherList: any[], //老师
  coursesList: any[] // 课程
  timeSlotList: any[] //时间
}

const LessonsSort: React.FC = () => {

  const { open, edit, rowId, openModal, closeModal, addModal, editModal, rowIdSelect, formRef, isPassed, isPassedModal } = useBseGeneraHook()
  const [formDataConfig, setFormDataConfig] = useState<any[]>([
    {
      type: "RangePicker",
      label: '月份',
      fieldName: 'month',
      placeholder: '请选择课程时间',
      rules: [{ required: true, message: '请选择课程时间' }],
    },
    {
      type: 'Select',
      label: '星期',
      fieldName: 'week',
      placeholder: '请选择星期',
      rules: [{ required: true, message: '请选择星期' }],
      child: [{
        value: '周一',
        label: '周一',
        key: '周一',
      }, {
        value: '周二',
        label: '周二',
        key: '周二',
      }, {
        value: '周三',
        label: '周三',
        key: '周三',
      }, {
        value: '周四',
        label: '周四',
        key: '周四',
      }, {
        value: '周五',
        label: '周五',
        key: '周五',
      }, {
        value: '周六',
        label: '周六',
        key: '周六',
      }, {
        value: '周日',
        label: '周日',
        key: '周日',
      }]
    },
    {
      type: 'InputNumber',
      label: '课程节数',
      fieldName: 'several',
      isDisabled: true
    },
    {
      type: 'Select',
      label: '教师',
      fieldName: 'teacher_id',
      placeholder: '请选择教师',
      rules: [{ required: true, message: '请选择教师' }],
      child: []
    },
    {
      type: 'Select',
      label: '教室',
      fieldName: 'class_room_id',
      placeholder: '请选择教室',
      rules: [{ required: true, message: '请选择教室' }],
      child: []
    },
    {
      type: 'Select',
      label: '课程',
      fieldName: 'course_id',
      placeholder: '请选择课程',
      rules: [{ required: true, message: '请选择课程' }],
      child: []
    },
    {
      type: 'Select',
      label: '上课时间',
      fieldName: 'timeSlotsId',
      placeholder: '请选择上课时间',
      rules: [{ required: true, message: '请选择上课时间' }],
      mode: 'multiple',
      allowClear: true,
      child: []
    },
  ])
  const [selectList, setSelectList] = useState<selectObject>({
    classRoomsList: [],
    teacherList: [],
    coursesList: [],
    timeSlotList: []
  })
  const [list, setList] = useState<any[]>([])
  const [total, setTotal] = useState<number>(1)
  const [search, setSearch] = useState<SearchType>({ limit: 10, page: 1 })
  const [formData, setFormData] = useState()

  const getAllSelect = async () => {
    const teacher = await teacherList() as any
    const classRoom = await classRoomsList() as any
    const course = await coursesList() as any
    const timeSlot = await timeSlotList() as any
    setSelectList({
      classRoomsList: classRoom.data,
      teacherList: teacher.data,
      coursesList: course.data,
      timeSlotList: timeSlot.data
    })
  }

  const getList = async () => {
    const res = await lessonsSort.list(search) as any
    setList(res.data.content)
    setTotal(res.data.totalElements)
  }

  useEffect(() => {
    getAllSelect()
  }, [])


  useEffect(() => {
    getList()
  }, [search])

  const rowEdit = (value: any) => {
    openModal()
    editModal()
    rowIdSelect(value.id)
    setFormData({
      ...value,
      timeSlotsId: value.timeSlots.map(item => item.timeSlot_id),
      // month: [moment(value.start_date, 'YYYY-MM-DD'), moment(value.end_date, 'YYYY-MM-DD')]
    })
    initSelect()
  }
  const del = (value: any) => {
    Modal.confirm({
      title: '确定删除',
      icon: null,
      okText: '是',
      cancelText: '否',
      onOk() {
        lessonsSort.del(value.id).then(res => {
          if (res.success) {
            getList()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const add = () => {
    openModal()
    addModal()
    initSelect()
  }
  const emitOnFinish = async (val: any) => {
    let res = null
    if (edit) {
      val.several = val.timeSlotsId.length
      val.start_date = val.month[0].format('YYYY-MM-DD')
      val.end_date = val.month[1].format('YYYY-MM-DD')
      res = await lessonsSort.created(val).catch(err => console.log(err)) as any
    } else {
      val.several = val.timeSlotsId.length
      val.start_date = val.month[0].format('YYYY-MM-DD')
      val.end_date = val.month[1].format('YYYY-MM-DD')
      res = await lessonsSort.upDate(rowId, val).catch(err => console.log(err))
    }
    if (res.success) {
      getList()
      closeModal()
      isPassedModal()
    } else {
      message.warning(res.message)
    }
  }

  const reset = () => {
    setSearch({ limit: 10, page: 1 })
    formRef.current?.resetFields();
  }
  const onSearch = (value: any) => {
    setSearch({ ...value, limit: 10, page: 1 })
  }
  const onPageChange = (page: number, pageSize: number) => {
    setSearch({ ...search, page: page || 1, limit: pageSize })
  }

  const filterSelect = (input: any, option: any) => {
    return option.children.indexOf(input) > 0
  }
  const initSelect = () => {
    formDataConfig.forEach(item => {
      switch (item.fieldName) {
        case 'teacher_id':
          item.child = selectList.teacherList
          break;
        case 'class_room_id':
          item.child = selectList.classRoomsList
          break;
        case 'course_id':
          item.child = selectList.coursesList
          break;
        case 'timeSlotsId':
          item.child = selectList.timeSlotList
          break;
      }
    })
    setFormDataConfig(formDataConfig)
  }
  return (
    <>
      <div>
        <Form layout='inline' onFinish={onSearch} ref={formRef}>

          <Form.Item name="class_room_id">
            <Select style={{ width: '100px' }} allowClear placeholder="教室名" showSearch
              filterOption={filterSelect}>
              {
                selectList.classRoomsList.map(c => {
                  return <Select.Option value={c.id} key={c.key}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>

          <Form.Item name="teacher_id" >
            <Select style={{ width: '100px' }} allowClear placeholder="教师名" showSearch filterOption={filterSelect}>
              {
                selectList.teacherList.map(c => {
                  return <Select.Option value={c.id} key={c.key}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>

          <Form.Item name="course_id">
            <Select style={{ width: '100px' }} allowClear placeholder="课程名" showSearch filterOption={filterSelect}>
              {
                selectList.coursesList.map(c => {
                  return <Select.Option value={c.id} key={c.key}>{c.label}</Select.Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name="blur">
            <Input placeholder="综合搜索" allowClear />
          </Form.Item>



          <Form.Item >
            <Button type="primary" htmlType="submit">搜索</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="primary" onClick={add}>添加</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="dashed" onClick={reset}>重置</Button>
          </Form.Item>
        </Form>
      </div >

      <div>
        <Table dataSource={list} pagination={false} rowKey="id"
          columns={[
            {
              title: '教室',
              key: 'class_room_name',
              render: (_: any, record: any) => (
                <><span>{record.classRoom.class_room_name}</span></>
              ),
            },
            {
              title: '课程属性',
              key: 'attribute',
              render: (_: any, record: any) => (
                <><span>{record.course.attribute}</span></>
              ),
            },
            {
              title: '课程名',
              key: 'attribute',
              render: (_: any, record: any) => (
                <><span>{record.course.name}</span></>
              ),
            },
            {
              title: '学分',
              key: 'credit',
              render: (_: any, record: any) => (
                <><span>{record.course.credit}</span></>
              ),
            },
            {
              title: '节数',
              dataIndex: 'several',
              key: 'several',
            },
            {
              title: '授课老师',
              key: 't_name',
              render: (_: any, record: any) => (
                <><span>{record.teacher.t_name}</span></>
              ),
            },
            {
              title: '每周',
              dataIndex: 'week',
              key: 'week',
            },
            {
              title: '上课时间',
              key: 'timeSlots',
              render: (_: any, record: any) => (
                <><span> {record.timeSlots[0].start_date + "-" + record.timeSlots[record.timeSlots.length - 1].start_date}</span></>
              ),
            },
            {
              title: '操作',
              key: 'option',
              render: (_: any, record: any) => (
                <>
                  <Button type="primary" onClick={() => rowEdit(record)}>编辑</Button>
                  <>&nbsp;</>
                  <Button type="primary" onClick={() => del(record)}>删除</Button>
                </>
              ),
            },
          ]}
        />
      </div>
      <div><Pagination showSizeChanger={true} total={total} onChange={onPageChange} /></div>

      <BaseGeneraForm
        title={edit ? '创建排课' : '查看排课'}
        open={open}
        isAdd={edit}
        footer={null}
        isPassed={isPassed}
        formData={formData}
        formDataConfig={formDataConfig}
        emitOnFinish={emitOnFinish}
        onCancel={closeModal} />
    </>
  );
}
export default LessonsSort